<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            background-color: gainsboro;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -100px;
            margin-left: -100px;
        }
        
        #move {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }
    </style>
    <script>
        window.onload = function() {
            var box = document.getElementById("box");
            var move = document.getElementById("move");
            // 鼠标按下，准备移动div
            move.onmousedown = function(ev) {
                ev = ev || event;
                var t = ev.clientY - move.offsetTop;
                var l = ev.clientX - move.offsetLeft;
                // 移动div
                document.onmousemove = function(ev) {
                    ev = ev || event;
                    // 计算要移动的div的left和top
                    var left = ev.clientX - l;
                    var top = ev.clientY - t;

                    move.style.left = left + "px";
                    move.style.top = top + "px";
                    //碰撞检测
                    // 写法一
                    // if (
                    //     left + move.offsetWidth < box.offsetLeft ||
                    //     left > box.offsetLeft + box.offsetWidth ||
                    //     top + move.offsetHeight < box.offsetTop ||
                    //     top > box.offsetTop + box.offsetHeight
                    // ) {
                    //     //表示没有碰撞到
                    //     box.style.background = 'gainsboro';
                    // } else {
                    //     box.style.background = 'orange';
                    // }
                    // 写法二
                    if (
                        left + move.offsetWidth >= box.offsetLeft &&
                        left <= box.offsetLeft + box.offsetWidth &&
                        top + move.offsetHeight >= box.offsetTop &&
                        top <= box.offsetTop + box.offsetHeight
                    ) {
                        //表示碰撞到了
                        box.style.background = 'orange';
                    } else {
                        box.style.background = 'gainsboro';
                    }
                }

            }
            move.onmouseup = function() {
                document.onmousemove = null;
            }

        }
    </script>
</head>

<body>
    <div id="box"></div>
    <div id="move"></div>
</body>

</html>